import re
import csv
import os
from collections import defaultdict

def parse_lib_pin_info(lib_dir):
    """
    解析 LIB 文件，获取每个 cell 的 pin 方向及电容信息。
    返回格式：{cell_type: {pin_name: {"direction": str, "FF": {"rise": float, "fall": float}, "SS": {"rise": float, "fall": float}}}}
    """
    pin_info = defaultdict(lambda: defaultdict(dict))

    # 遍历 LIB 目录下的所有文件
    for root, _, files in os.walk(lib_dir):
        for file in files:
            if not file.endswith(".lib"):
                continue

            # 从文件名中提取工艺角（FF/SS）
            corner = "FF" if "_FF_" in file else "SS" if "_SS_" in file else None
            if not corner:
                continue  # 忽略非 FF/SS 文件

            lib_path = os.path.join(root, file)
            with open(lib_path, 'r', encoding='utf-8', errors='ignore') as f:
                lines = f.readlines()

            collecting_cell = False
            collecting_pin = False
            brace_count = 0  # 追踪大括号层级
            cell_name = None
            pin_name = None
            cell_content = []
            pin_content = []

            for line in lines:
                line = line.strip()

                # 检测 cell (XXX) { 的开始
                cell_match = re.match(r'cell\s*\(\s*"?(.*?)"?\s*\)\s*\{', line)
                if cell_match and not collecting_cell:
                    collecting_cell = True
                    brace_count = 1  # 进入第一个 `{`
                    cell_name = cell_match.group(1)
                    cell_content = [line]
                    continue

                if collecting_cell:
                    cell_content.append(line)

                    # 处理大括号计数
                    brace_count += line.count("{")
                    brace_count -= line.count("}")

                    # 检测 cell 结束
                    if brace_count == 0:
                        collecting_cell = False
                        cell_text = "\n".join(cell_content)

                        # 解析 pin (XXX) { 结构
                        for pin_line in cell_text.split("\n"):
                            pin_match = re.match(r'pin\s*\(\s*"?(.*?)"?\s*\)\s*\{', pin_line)
                            if pin_match and not collecting_pin:
                                collecting_pin = True
                                pin_name = pin_match.group(1)
                                pin_content = [pin_line]
                                brace_count = 1
                                continue

                            if collecting_pin:
                                pin_content.append(pin_line)
                                brace_count += pin_line.count("{")
                                brace_count -= pin_line.count("}")

                                if brace_count == 0:
                                    collecting_pin = False
                                    pin_text = "\n".join(pin_content)

                                    # 初始化数据结构
                                    if pin_name not in pin_info[cell_name]:
                                        pin_info[cell_name][pin_name] = {
                                            "direction": None,
                                            "FF": {"rise": 0.0, "fall": 0.0},
                                            "SS": {"rise": 0.0, "fall": 0.0}
                                        }

                                    # 提取 pin 方向
                                    direction_match = re.search(r'direction\s*:\s*"?(.*?)"?\s*;', pin_text, re.IGNORECASE)
                                    if direction_match:
                                        pin_info[cell_name][pin_name]["direction"] = direction_match.group(1).lower()

                                    # 解析电容值（仅当前工艺角）
                                    rise_match = re.search(r'rise_capacitance\s*:\s*([\d.]+)\s*;', pin_text, re.IGNORECASE)
                                    fall_match = re.search(r'fall_capacitance\s*:\s*([\d.]+)\s*;', pin_text, re.IGNORECASE)

                                    if rise_match:
                                        pin_info[cell_name][pin_name][corner]["rise"] = float(rise_match.group(1))
                                    if fall_match:
                                        pin_info[cell_name][pin_name][corner]["fall"] = float(fall_match.group(1))

                                    # 输出引脚电容强制设为 0（除非明确指定）
                                    if pin_info[cell_name][pin_name]["direction"] == "output":
                                        pin_info[cell_name][pin_name][corner]["rise"] = 0.0
                                        pin_info[cell_name][pin_name][corner]["fall"] = 0.0

    return pin_info

def test():
    # 示例调用
    def_file = "/home/hujiahui/git/paper/dataset/aes_cipher/asap7/innovus/log/cts.def"
    lib_dir = "/home/hujiahui/case_work/prase_platfrom/asap7/lib"  # 替换为 LIB 文件目录
    output_csv = "/home/hujiahui/test/test_prase/pins.csv"
    output_debug_csv = "/home/hujiahui/test/test_prase/lib_prase_result.csv"  # 新增的调试 CSV 文件路径


    pin_info = parse_lib_pin_info(lib_dir)
    # 保存到 CSV 文件（调试用）
    with open(output_debug_csv, 'w', newline='') as csvfile:
        writer = csv.writer(csvfile)
        writer.writerow(["Cell Type", "Pin Name", "Direction", "FF_rise", "FF_fall", "SS_rise", "SS_fall"])
        for cell_type in pin_info:
            for pin_name in pin_info[cell_type]:
                cap_data = pin_info[cell_type][pin_name]
                writer.writerow([
                    cell_type,
                    pin_name,
                    cap_data["direction"],
                    cap_data["FF"]["rise"],
                    cap_data["FF"]["fall"],
                    cap_data["SS"]["rise"],
                    cap_data["SS"]["fall"]
                ])
    print(f"LIB pin info saved to: {output_debug_csv}")

if __name__ == "__main__":
    test()